package com.linxiao.hrcrm.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.linxiao.hrcrm.domain.CrmBalanceFlow;
import com.linxiao.hrcrm.domain.CrmCustomer;
import com.linxiao.hrcrm.service.ICrmBalanceFlowService;
import com.linxiao.hrcrm.service.ICrmCustomerService;
import com.linxiao.hrcrm.vo.CashOutRequest;
import com.linxiao.payment.business.TransferManager;
import com.linxiao.payment.core.constants.IfCodeEnum;
import com.linxiao.payment.enums.PayMethodEnums;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.linxiao.hrcrm.mapper.CrmCustomerBalanceMapper;
import com.linxiao.hrcrm.domain.CrmCustomerBalance;
import com.linxiao.hrcrm.service.ICrmCustomerBalanceService;

import javax.annotation.Resource;

/**
 * 客户余额记录Service业务层处理
 *
 * @author zhoudong
 * @date 2024-01-03
 */
@Service
public class CrmCustomerBalanceServiceImpl implements ICrmCustomerBalanceService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private CrmCustomerBalanceMapper crmCustomerBalanceMapper;
    @Resource
    private ICrmCustomerService crmCustomerService;
    @Resource
    private ICrmBalanceFlowService crmBalanceFlowService;
    @Resource
    private Map<String, TransferManager> transferManagerMap;

    /**
     * 查询客户余额记录
     *
     * @param id 客户余额记录主键
     * @return 客户余额记录
     */
    @Override
    public CrmCustomerBalance selectCrmCustomerBalanceById(Long id) {
        return crmCustomerBalanceMapper.selectCrmCustomerBalanceById(id);
    }

    /**
     * 查询客户余额记录列表
     *
     * @param crmCustomerBalance 客户余额记录
     * @return 客户余额记录
     */
    @Override
    public List<CrmCustomerBalance> selectCrmCustomerBalanceList(CrmCustomerBalance crmCustomerBalance) {
        List<CrmCustomerBalance> crmCustomerBalances = crmCustomerBalanceMapper.selectCrmCustomerBalanceList(crmCustomerBalance);
        if (CollUtil.isNotEmpty(crmCustomerBalances)) {
            crmCustomerBalances.parallelStream().forEach(ccb -> {
                CrmCustomer crmCustomer = crmCustomerService.selectCrmCustomerById(ccb.getCustomerId());
                if (crmCustomer != null) {
                    ccb.setCustomerName(crmCustomer.getCustomerName());
                } else {
                    ccb.setCustomerName("未知");
                }
            });
        }
        return crmCustomerBalances;
    }

    /**
     * 新增客户余额记录
     *
     * @param crmCustomerBalance 客户余额记录
     * @return 结果
     */
    @Override
    public int insertCrmCustomerBalance(CrmCustomerBalance crmCustomerBalance) {
        crmCustomerBalance.setCreateTime(DateUtils.getNowDate());
        crmCustomerBalance.setRemark("新增余额：" + crmCustomerBalance.getBalanceAmount().toString());
        return crmCustomerBalanceMapper.insertCrmCustomerBalance(crmCustomerBalance);
    }

    /**
     * 修改客户余额记录
     *
     * @param crmCustomerBalance 客户余额记录
     * @return 结果
     */
    @Override
    public int updateCrmCustomerBalance(CrmCustomerBalance crmCustomerBalance) {
        crmCustomerBalance.setUpdateTime(DateUtils.getNowDate());
        crmCustomerBalance.setRemark("新增余额：" + crmCustomerBalance.getBalanceAmount().toString());
        return crmCustomerBalanceMapper.updateCrmCustomerBalance(crmCustomerBalance);
    }

    /**
     * 批量删除客户余额记录
     *
     * @param ids 需要删除的客户余额记录主键
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerBalanceByIds(Long[] ids) {
        return crmCustomerBalanceMapper.deleteCrmCustomerBalanceByIds(ids);
    }

    /**
     * 删除客户余额记录信息
     *
     * @param id 客户余额记录主键
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerBalanceById(Long id) {
        return crmCustomerBalanceMapper.deleteCrmCustomerBalanceById(id);
    }

    /**
     * 根据客户ID查询
     * @param customerId
     * @return
     */
    @Override
    public CrmCustomerBalance selectByCustomerId(Long mchId, Long customerId) {
        CrmCustomerBalance query = new CrmCustomerBalance();
        query.setCustomerId(customerId);
        query.setBalanceType(CrmCustomerBalance.BALANCE_TYPE_BALANCE);
        query.setMchId(mchId);
        List<CrmCustomerBalance> crmCustomerBalances = crmCustomerBalanceMapper.selectCrmCustomerBalanceList(query);
        if (CollUtil.isNotEmpty(crmCustomerBalances)) {
            return crmCustomerBalances.get(0);
        }
        return null;
    }

    /**
     * 根据客户ID查询，如果不存在，就插入
     * @param mchId
     * @param customerId
     * @return
     */
    @Override
    public CrmCustomerBalance selectByCustomerIdAndInsert(Long mchId, Long customerId) {
        CrmCustomerBalance crmCustomerBalance = selectByCustomerId(mchId, customerId);
        if (crmCustomerBalance == null) {
            crmCustomerBalance = new CrmCustomerBalance();
            crmCustomerBalance.setMchId(mchId);
            crmCustomerBalance.setBalanceAmount(BigDecimal.ZERO);
            crmCustomerBalance.setBalanceType(CrmCustomerBalance.BALANCE_TYPE_BALANCE);
            crmCustomerBalance.setCustomerId(customerId);
            insertCrmCustomerBalance(crmCustomerBalance);
            return crmCustomerBalance;
        }
        return crmCustomerBalance;
    }

    /**
     * 提现
     * @param cashOutRequest
     * @return
     */
    @Override
    public AjaxResult cashOut(CashOutRequest cashOutRequest) {
        // 获取渠道代码
        IfCodeEnum ifCodeEnum = IfCodeEnum.getByInsCode(cashOutRequest.getIfCode());
        if (ifCodeEnum == null) {
            return AjaxResult.error("提现渠道代码有误");
        }
        // 用户身份认证
        CrmCustomer crmCustomer = crmCustomerService.selectCrmCustomerById(cashOutRequest.getCustomerId());
        if (crmCustomer == null) {
            return AjaxResult.error("客户身份信息有误");
        }
        if (StrUtil.isBlank(crmCustomer.getMemberId())) {
            return AjaxResult.error("该客户暂未绑定会员，请联系工作人员绑定");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (!crmCustomer.getMemberId().equals(loginUser.getUserId())) {
            return AjaxResult.error("非法请求！");
        }

        // 获取余额
        CrmCustomerBalance crmCustomerBalance = selectByCustomerId(cashOutRequest.getMchId(), cashOutRequest.getCustomerId());
        // 核对提现金额
        if (crmCustomerBalance == null || crmCustomerBalance.getBalanceAmount().compareTo(cashOutRequest.getCashOutAmount()) == -1) {
            return AjaxResult.error("可提现余额不足");
        }

        // 增加余额变动记录
        CrmBalanceFlow crmBalanceFlow = new CrmBalanceFlow();
        crmBalanceFlow.setCustomerId(crmCustomerBalance.getCustomerId());
        crmBalanceFlow.setPreviousBalance(crmCustomerBalance.getBalanceAmount());
        BigDecimal currentBalance = crmCustomerBalance.getBalanceAmount().subtract(cashOutRequest.getCashOutAmount());
        crmBalanceFlow.setCurrentBalance(currentBalance);
        String outOrderId = IdUtil.getSnowflakeNextId() + "";
        crmBalanceFlow.setBusinessOrderId(outOrderId);
        crmBalanceFlow.setAccountType(CrmBalanceFlow.ACCOUNT_TYPE_BALANCE);
        crmBalanceFlow.setMchId(cashOutRequest.getMchId());
        crmBalanceFlow.setRemark(JSON.toJSONString(cashOutRequest));
        crmBalanceFlowService.insertCrmBalanceFlow(crmBalanceFlow);

        // 扣减余额
        crmCustomerBalance.setBalanceAmount(currentBalance);
        crmCustomerBalanceMapper.updateCrmCustomerBalance(crmCustomerBalance);

        // 调用接口提现
        PayMethodEnums payMethodEnumsByInsCode = PayMethodEnums.getPayMethodEnumsByInsCode(ifCodeEnum.getInsCode());
        TransferManager transferManager = transferManagerMap.get(payMethodEnumsByInsCode.getService());

        // TODO 提现未完成，得根据实际提现，组装参数
        /*Map<String, Object> transfer = transferManager.transfer();
        logger.info("提现，返回：{}", JSON.toJSONString(transfer));*/
        return null;
    }

    /**
     * 我的余额
     * @param crmCustomerBalance
     * @return
     */
    @Override
    public List<CrmCustomerBalance> findByUser(CrmCustomerBalance crmCustomerBalance) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        CrmCustomer customer = crmCustomerService.selectCrmCustomerByMemberId(crmCustomerBalance.getMchId(), loginUser.getUserId());
        if (customer == null) {
            throw new UtilException("客户信息有误");
        }
        crmCustomerBalance.setCustomerId(customer.getId());

        List<CrmCustomerBalance> crmCustomerBalances = crmCustomerBalanceMapper.selectCrmCustomerBalanceList(crmCustomerBalance);
        if (CollUtil.isNotEmpty(crmCustomerBalances)) {
            crmCustomerBalances.parallelStream().forEach(c -> c.setCustomerName(customer.getCustomerName()));
        }
        return crmCustomerBalances;
    }
}
